<template>
  <div class="movie-platform">
    <!-- 🔍 搜索栏 -->
    <div class="search-bar">
      <input
        type="text"
        v-model="keyword"
        placeholder="搜索电影名称 / 类型 / 导演 / 演员 / 描述"
        @keyup.enter="handleSearch"
      />
      <button @click="handleSearch">搜索</button>
    </div>

    <!-- 主体内容 -->
    <main class="main">
      <div class="main-inner">
        <div class="left-column" style="flex: 1">
          <!--  搜索结果区域 -->
          <section v-if="isSearching" class="search-result">
            <div class="section-header">
              <h2>搜索结果</h2>
              <!-- 调试信息
              <div style="font-size: 12px; color: red;">
                调试: isSearching={{ isSearching }}, 结果数量={{ searchMovies.length }}
              </div> -->
              <button class="all" @click="clearSearch">返回首页</button>
            </div>

            <div class="movies-list">
              <template v-if="searchMovies.length > 0">
                <div
                  v-for="movie in searchMovies"
                  :key="movie.movieId"
                  class="movie-item"
                >
                  <img :src="movie.movieImage" alt="电影海报" class="poster" />
                  <div class="movie-info">
                    <h3 class="movie-title">{{ movie.movieName }}</h3>
                    <div class="movie-score">评分: {{ movie.movieScore }}</div>
                    <button @click="goToMovieDetail(movie)" class="buy-ticket">
                      购票
                    </button>
                  </div>
                </div>
              </template>

              <!-- 没有结果时 -->
              <div v-else class="no-result">
                😢 未找到相关影片，请尝试其他关键词。
                <div style="font-size: 12px; margin-top: 10px">
                  搜索状态: isSearching={{ isSearching }}, searchMovies长度={{
                    searchMovies.length
                  }}
                </div>
              </div>
            </div>
          </section>

          <!--  默认首页（正在热映 + 即将上映） -->
          <template v-else>
            <!-- 正在热映 -->
            <section class="showing-movies">
              <div class="section-header">
                <h2>正在热映</h2>
                <router-link to="/movieList">
                  <a href="#" class="all">全部</a>
                </router-link>
              </div>

              <div class="movies-list">
                <div
                  v-for="movie in showingMovies"
                  :key="movie.movieId"
                  class="movie-item"
                >
                  <img :src="movie.movieImage" alt="电影海报" class="poster" />
                  <div class="movie-info">
                    <h3 class="movie-title">{{ movie.movieName }}</h3>
                    <div class="movie-score">评分: {{ movie.movieScore }}</div>
                    <button @click="goToMovieDetail(movie)" class="buy-ticket">
                      购票
                    </button>
                  </div>
                </div>
              </div>
            </section>

            <!-- 即将上映 -->
            <section class="coming-soon">
              <div class="section-header">
                <h2>即将上映</h2>
                <router-link to="/movieList">
                  <a href="#" class="all">全部</a>
                </router-link>
              </div>

              <div class="movies-list">
                <div
                  v-for="movie in comingSoonMovies"
                  :key="movie.movieId"
                  class="movie-item"
                >
                  <img :src="movie.movieImage" alt="电影海报" class="poster" />
                  <div class="movie-info">
                    <h3 class="movie-title">{{ movie.movieName }}</h3>
                    <div class="want-to-see">
                      {{ movie.wantToSee || 0 }}人想看
                    </div>
                    <div class="movie-tags">
                      <span class="tag">预告片</span>
                      <span class="tag pre-sale" @click="goToMovieDetail(movie)"
                        >预售</span
                      >
                    </div>
                    <div class="release-date">{{ movie.releaseDate }}上映</div>
                  </div>
                </div>
              </div>
            </section>
          </template>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { getHotMoviesByStatus } from "@/api/movie";
import { getMovieDetailByKeyword } from "@/api/movieDetail";

// 确保这些是响应式引用
const showingMovies = ref([]);
const comingSoonMovies = ref([]);
const searchMovies = ref([]);
const keyword = ref("");
const isSearching = ref(false);

const router = useRouter();

// 初始化加载数据
onMounted(() => {
  getHotMovies(1);
  getHotMovies(2);
});

// 加载电影数据（状态 1=热映，2=即将上映）
async function getHotMovies(status) {
  try {
    const res = await getHotMoviesByStatus(status);
    console.log("🎬 加载电影状态", status, "返回:", res.data);
    if (res.data.code === 200) {
      const list = res.data.data || [];
      if (status === 1) showingMovies.value = list;
      else comingSoonMovies.value = list;
    }
  } catch (err) {
    console.error("请求失败:", err);
  }
}
// 🔍 搜索
async function handleSearch() {
  console.log("handleSearch函数被触发了！");
  const kw = keyword.value.trim();
  console.log("🔍 用户输入关键词:", kw);
  if (!kw) return;

  try {
    const res = await getMovieDetailByKeyword(kw);
    console.log("🔍 搜索接口完整响应:", res);
    console.log("🔍 搜索接口返回数据:", res.data);

    let data = [];

    // 处理不同的返回数据结构
    if (Array.isArray(res.data)) {
      // 直接返回数组的情况
      data = res.data;
    } else if (res.data && res.data.code === 200) {
      // 返回 {code: 200, data: [...]} 的情况
      data = res.data.data || [];
    } else if (res.data && Array.isArray(res.data.list)) {
      // 返回 {list: [...]} 的情况
      data = res.data.list;
    }

    console.log("✅ 最终解析的数据:", data);

    if (data.length > 0) {
      searchMovies.value = data.map((m) => ({
        movieId: m.movieDetailId || m.movieId,
        movieName: m.movieName,
        movieScore: m.score || "暂无评分",
        movieImage:
          m.movieImage ||
          m.images ||
          "https://via.placeholder.com/200x280?text=暂无海报",
        releaseDate: m.releaseTime || "",
        boxOffice: m.boxOffice || "",
        wantToSee: m.wantToSee || 0,
      }));

      console.log("✅ 映射后的搜索结果:", searchMovies.value);
      isSearching.value = true;
    } else {
      searchMovies.value = [];
      isSearching.value = true;
      console.log("⚠️ 搜索结果为空");
    }
  } catch (err) {
    console.error("搜索请求失败:", err);
    searchMovies.value = [];
    isSearching.value = true;
  }
}
// 返回首页
function clearSearch() {
  keyword.value = "";
  isSearching.value = false;
  searchMovies.value = [];
  getHotMovies(1);
  getHotMovies(2);
}

// 输入框清空时自动返回
watch(keyword, (val) => {
  if (!val.trim() && isSearching.value) {
    clearSearch();
  }
});

// 跳转电影详情页
function goToMovieDetail(movie) {
  router.push({
    path: "/movieDetail",
    query: {
      movieId: movie.movieId,
      movieName: movie.movieName,
      moviePoster: movie.movieImage,
      score: movie.movieScore,
      boxOffice: movie.boxOffice || "",
      releaseDate: movie.releaseDate || "",
    },
  });
}
</script>

<style scoped>
.movie-platform {
  font-family: "Microsoft YaHei", sans-serif;
  color: #333;
}

/* 搜索栏 */
.search-bar {
  width: 1200px;
  margin: 20px auto;
  display: flex;
  justify-content: center;
  align-items: center;
}
.search-bar input {
  width: 500px;
  height: 38px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 4px 0 0 4px;
  outline: none;
  font-size: 14px;
}
.search-bar input:focus {
  border-color: #a2131d;
}
.search-bar button {
  height: 40px;
  padding: 0 25px;
  background-color: #a2131d;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}
.search-bar button:hover {
  background-color: #8a1018;
}

/* 主体内容 */
.main {
  background-color: #f5f5f5;
  padding: 20px 0;
}
.main-inner {
  display: flex;
  width: 1200px;
  margin: 0 auto;
}
.left-column {
  display: flex;
  flex-direction: column;
}

/* 区块头 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.section-header h2 {
  font-size: 20px;
  margin: 0;
}
.all {
  color: #0078d7;
  text-decoration: none;
}

/* 电影卡片 */
.movies-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  gap: 20px;
}
.movie-item {
  width: 200px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}
.movie-item:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}
.poster {
  width: 100%;
  height: 280px;
  object-fit: cover;
  border-bottom: 1px solid #eee;
}
.movie-info {
  text-align: center;
  padding: 10px 8px;
}
.movie-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin: 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.movie-score {
  color: #e67e22;
  font-weight: bold;
  margin-bottom: 8px;
}
.buy-ticket {
  background-color: #a2131d;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s ease;
}
.buy-ticket:hover {
  background-color: #c01b25;
}

/* 即将上映 */
.want-to-see {
  color: #e54847;
  margin: 5px 0;
}
.movie-tags {
  display: flex;
  justify-content: center;
  margin-bottom: 5px;
}
.tag {
  margin: 0 5px;
  color: #999;
}
.tag.pre-sale {
  color: #0078d7;
}
.release-date {
  color: #666;
  font-size: 14px;
}

/* 搜索结果 */
.no-result {
  text-align: center;
  font-size: 16px;
  color: #666;
  padding: 60px 0;
}
.search-result .section-header .all {
  display: block !important;
  background-color: #a2131d;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}
.search-result .section-header .all:hover {
  display: block !important;
  background-color: #8a1018;
}
</style>
